package com._54programer.demo.ws;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com._54programer.ws.NBind;

/**
 * @author SN
 * @date Created by on 2019/11/29
 * @description
 * 处理消息的handler
 * TextWebSocketFrame：在netty中，是用于为websocket专门处理文本的对象，frame是消息的载体
 */
public class WsServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    //保存和管理所有客户端的channel
    public static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        //1.获取客户端发送的消息
        String content = msg.text();
        Channel channel = ctx.channel();

        //2.回复客户端消息
        ctx.writeAndFlush(new TextWebSocketFrame("hello ws "+ LocalDateTime.now()));

        //3.群发
        //3.1方式一
//        for (Channel channel : clients){
//            channel.writeAndFlush(new TextWebSocketFrame(ctx.channel().id() + "的消息: "+ content));
//        }
        //3.2方式2
        clients.writeAndFlush(new TextWebSocketFrame(channel.id() + "的消息: "+ content));
        
        
    }

    /**
     * 有新客户端连接服务端
     * 获取客户端channel, 添加到ChannelGroup中去管理
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("上线: " +ctx.channel().id());
        clients.add(ctx.channel());
    }

    /**
     * 客户端离开
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //handlerRemoved被触发时会自动从ChannelGroup中移除对应客户端channel
        System.out.println("离线长ID: "+ctx.channel().id().asLongText());
        System.out.println("离线短ID: "+ctx.channel().id().asShortText());
    }

    /**
     * 异常
     * 1.关闭channel
     * 2.从ChannelGroup移除
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
        clients.remove(ctx.channel());
    }
}
